#
# Copyright (c) 2024 Black Sesame Technologies
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os
import re
from string import Template

DALIDL_TYPESUPPORT_CPP_ITEM_PATTERN = "${BUILD_DIR}/${PKG_NAME}/dalidl_typesupport_cpp/${PKG_NAME}/msg/"
DALIDL_TYPESUPPORT_FASTRTPS_CPP_ITEM_PATTERN = "${BUILD_DIR}/${PKG_NAME}/dalidl_typesupport_fastrtps_cpp/${PKG_NAME}/msg/detail/dds_fastrtps/"
DALIDL_TYPESUPPORT_INTROSPECTION_CPP_ITEM_PATTERN = "${BUILD_DIR}/${PKG_NAME}/dalidl_typesupport_introspection_cpp/${PKG_NAME}/msg/detail/"

idl_filenames = []

def get_idl_filenames_underline(path):
    msg_directory = os.path.join(path, 'msg')
    idl_list = []

    if os.path.exists(msg_directory) and any(file.endswith('.idl') for file in os.listdir(msg_directory)):
        for filename in os.listdir(msg_directory):
            if filename.endswith('.idl'):
                idl_list.append(filename)
    
    return idl_list

def trans_to_underline(original_name):
    converted_name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', original_name)
    converted_name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', converted_name)
    converted_name = converted_name.lower()
    return converted_name

def remove_trailing_slash(input_string):
    while input_string.endswith('/') or input_string.endswith('\\'):
        input_string = input_string[:-1]
    return input_string

def cmake_gen(path):
    current_dir = os.path.dirname(os.path.abspath(__file__))

    template_file = current_dir + '/resource/cmake/CMakeLists.txt.template'

    path = remove_trailing_slash(path)

    with open(template_file, 'r') as f:
        template_content = f.read()
    
    template = Template(template_content)
    idl_filenames_underline = get_idl_filenames_underline(path)

    # dalidl_typesupport_cpp
    typesupport_items_files = []
    for filename in idl_filenames_underline:
        typesupport_items_files.append(DALIDL_TYPESUPPORT_CPP_ITEM_PATTERN + trans_to_underline(filename)[:-4] + "__type_support.cpp")

    typesupport_items = '\n    '.join(typesupport_items_files)
    # print(typesupport_items)

    # dalidl_typesupport_fastrtps_cpp
    fastrtps_items_files = []
    for filename in idl_filenames_underline:
        fastrtps_items_files.append(DALIDL_TYPESUPPORT_FASTRTPS_CPP_ITEM_PATTERN + trans_to_underline(filename)[:-4] + "__type_support.cpp")

    fastrtps_items = '\n    '.join(fastrtps_items_files)
    # print(fastrtps_items)

    # dalidl_typesupport_introspection_cpp
    introspection_items_files = []
    for filename in idl_filenames_underline:
        introspection_items_files.append(DALIDL_TYPESUPPORT_INTROSPECTION_CPP_ITEM_PATTERN + trans_to_underline(filename)[:-4] + "__type_support.cpp")

    introspection_items = '\n    '.join(introspection_items_files)
    # print(introspection_items)

    build_dir = os.path.join(current_dir, 'build')
    build_dir_abs = os.path.abspath(build_dir)

    project_dir = os.path.dirname(current_dir)
    include_dir = os.path.join(project_dir, "dal_msg", "include")
    include_dir_abs = os.path.abspath(include_dir)

    src_dir = os.path.join(project_dir, "dal_msg", "src")
    src_dir_abs = os.path.abspath(src_dir)

    print("build_dir_abs: " + build_dir_abs)
    print("include_dir_abs: " + include_dir_abs)
    print("src_dir_abs: " + src_dir_abs)

    pkg_name = os.path.basename(path)
    template_str1 = template.safe_substitute(DALIDL_TYPESUPPORT_ITEMS=typesupport_items,
                                   DALIDL_TYPESUPPORT_FASTRTPS_ITEMS=fastrtps_items,
                                   DALIDL_TYPESUPPORT_INTROSPECTION_ITEMS=introspection_items)
    template_str2 = Template(template_str1).safe_substitute(BUILD_DIR=build_dir_abs,
                                                            PKG_NAME=pkg_name,
                                                            INCLUDE_DIR=include_dir_abs,
                                                            SRC_DIR=src_dir_abs)

    output_file = build_dir + "/" + pkg_name + "/CMakeLists.txt"
    with open(output_file, 'w') as f:
        f.write(template_str2)
    
    print("[CMakeLists.txt] generate code succeed.")
